import { Component, HostListener, OnDestroy, OnInit } from "@angular/core";
import { CommService } from "../comm-service";
import * as e from "echarts";
import { MyhttpService } from "../myhttp.service";
import { max } from "rxjs/internal/operators";
import { sjgzxinModuledatas } from "../pubcomponent/pageTitle.datas";

declare var $: any;

@Component({
  template: `
  <div class="all_bg">
    <div class="">
      <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
      </div>
      <div class="portlet-body">
        <div class="row">
          <form class="form-horizontal" role="form">
            <div class="col-lg-6 col-lg-offset-4">
              <div class="form-group">
                <label class="control-label col-lg-3">查询时间：</label>
                <div class="col-lg-3">
                  <select class="form-control bselect" id="fzlx" (change)="FzlxChange()">
                    <option value="month">按月统计</option>
                    <option value="day">按天统计</option>
                  </select>
                </div>
                <div class="col-lg-6" id="MonthRoom">
                  <div class="input-group">
                    <select id="bDate" (change)="dateChange('b')"></select>
                    <span class="input-group-addon" style="width: 0.1%">至</span>
                    <select id="eDate" (change)="dateChange('e')"></select>
                  </div>
                </div>
                <div class="col-lg-6" id="DayRoom">
                  <div class="input-group input-daterange">
                    <input type="text" class="form-control dateB_content" readonly>
                    <div class="input-group-addon">至</div>
                    <input type="text" class="form-control dateE_content" readonly>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-2">
              <button type="button" class="btn blue" (click)="inittable_dzbq()">
                <i class="fa fa-search"></i> 搜索
              </button>
              &nbsp;&nbsp;
              <button type="button" class="btn default" (click)="resetSearchForm()">
                重置
              </button>
            </div>
          </form>
        </div>
        <div class="row">
          <div class="col-lg-12">
            <table id="ll_dzbqtable" [style.minWidth]="mintablewidth"></table>
          </div>
        </div>
      </div>
    </div>

    <div class="modal fad" id="lineChartModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog bigmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">标签流量统计图</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-lg-12">
                <div id="lineChart"></div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">确 定</button>
          </div>
        </div>
      </div>
    </div>
    </div>
  `,
  styles: [
    "#DayRoom{display: none}",
    ".chartbtn{text-align: right;font-size: 20px;color: #1477F3;cursor: pointer}",
    "#lineChart{width:calc(1200px - 30px);height: 450px}"
  ]
})
export class LlDzbqComponent implements OnInit, OnDestroy {
  mintablewidth: string = "0px";
  userinfo: any;
  actionobj1: any[] = [];
  sjb_btns: any[] = ["bqll_dc", "bqll_zxt"];
  sjb_c_btns: any[] = ["zxt_bq"];
  hascbtns: any[] = [];

  s_obj: any = {
    sblx: "dzbqsb",
    fzlx: "month",
    kssj: "",
    jssj: '',
  };
  dc_obj: any = {
    sblx: "dzbqsb",
    fzlx: "month",
    kssj: "",
    jssj: "",
  };
  searchTimeRangeMax_month: number = 12;
  searchTimeRangeMax_day: number = 30;
  caozuo_bqid: string = "";
  chart: any;

  /**
   * 初始化按钮
   */
  initactions(): void {
    // this.commservice.getroleBtns(this.sjb_btns, this.sjb_c_btns, this.userinfo.nowroleid, "table_bqll", (hasportbtns, hastablebtns) => {
    //   this.actionobj1 = hasportbtns;
    //   this.hascbtns = hastablebtns;
    // });
    this.commservice.getroleBtns_not_permissions(this.sjb_btns, this.sjb_c_btns, "table_bqll", (hasportbtns, hastablebtns) => {
      this.actionobj1 = hasportbtns;
      this.hascbtns = hastablebtns;
    });
  }

  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;
    const actiontype = e.type;
    if (fromv === "table_bqll") {
      if (actiontype === "dc") {
        // 导出
        this.exportExcel();
      } else if (actiontype === "zxt") {
        // 所有终端的 流量和折线图
        this.showallLinechart();
      }
    }
  }


  exportExcel(): void {
    const url = 'sjgz/sbwb/dcsbsyllExcel';
    this.commservice.blockUI({
      boxed: true,
      message: "导出中...",
      zIndex: 10051,
      overlayColor: "#67809F"
    });
    this.itservice.kwPtPost(url, this.dc_obj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const url = resp ? resp.dcwjlj : "";
            if (url) {
              this.commservice.downFile(url, "", "");
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        }
      });
    })
  }

  /**
   * 电子标签流量表格
   */
  inittable_dzbq(): void {
    const that = this;
    let rangeDateList: any[];
    if (this.s_obj.fzlx == "month") {
      const b1 = $("#bDate").selectpicker("val");
      const e1 = $("#eDate").selectpicker("val");
      this.s_obj.kssj = b1;
      this.s_obj.jssj = e1;
      const blarr = b1.split("-");
      const elarr = e1.split("-");
      rangeDateList = this.commservice.rangeDays_moth(new Date(blarr[0], Number(blarr[1]) - 1, 1), new Date(elarr[0], Number(elarr[1]) - 1, 1));
    } else if (this.s_obj.fzlx == "day") {
      const b2 = $(".dateB_content").eq(0).datepicker("getDate");
      const e2 = $(".dateE_content").eq(0).datepicker("getDate");
      this.s_obj.kssj = this.commservice.YMD_get(b2);
      this.s_obj.jssj = this.commservice.YMD_get(e2);
      rangeDateList = this.commservice.rangeDays_day(b2, e2);
    }
    this.dc_obj.fzlx = this.s_obj.fzlx;
    this.dc_obj.kssj = this.s_obj.kssj;
    this.dc_obj.jssj = this.s_obj.jssj;
    const columnList: any[] = [];
    let mintablewidthInit: number = 0;
    columnList.push({
      title: "序号",
      field: "xh",
      width: 60
    });
    mintablewidthInit += 60;
    columnList.push({
      title: "标签ID",
      field: "sbid",
      width: 150
    });
    mintablewidthInit += 150;
    // 动态列
    rangeDateList.forEach((datev) => {
      columnList.push({
        title: datev,
        field: datev,
        width: 100
      });
      mintablewidthInit += 100;
    });
    columnList.push({
      title: "总量(KB)",
      field: "zyl",
      width: 100,
      events: this.myevents,
      formatter: function (v) {
        let str = "";
        str += v;
        if (that.hascbtns.indexOf("zxt_bq") != -1) {
          str += "<span style='cursor: pointer;display: inline-block;padding-left: 10px;color:#1477F3 ' class='linechart'><i class='fa fa-line-chart'></i></span>";
        }
        return str;
      }
    });
    mintablewidthInit += 100;
    this.mintablewidth = `${mintablewidthInit}px`;
    console.log('columnList', columnList);


    $('#ll_dzbqtable').bootstrapTable('destroy');
    $('#ll_dzbqtable').bootstrapTable({
      classes: 'table  table-bordered fixed-table-header', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      sidePagination: "server", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 10, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [10, 20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      //paginationPreText: '上一页', //默认是&lsaquo;
      //paginationNextText: '下一页', //默认是&rsaquo;
      //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
      //设置为limit可以获取limit, offset, search, sort, order
      method: "post",
      url: 'sjgz/sbwb/sbsyllcx',
      cache: false,
      contentType: 'application/json;utf-8',
      queryParamsType: "undefined",
      height: this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50,
      columns: columnList,
      ajax: function (param) {
        // 使用表格组件的加获取数据的加载效果（portlet 右上角的按钮等不能操作）
        that.commservice.blockUI({
          target: ".loadData",
          boxed: true,
          message: "数据获取中...",
          zIndex: 10051,
          overlayColor: "#67809F"
        });
        const url = "sjgz/sbwb/sbsyllcx";
        const reqobj = that.s_obj;
        const nowreqobj = {};
        nowreqobj["pageNum"] = param.data.pageNumber;
        nowreqobj["pageSize"] = param.data.pageSize;
        nowreqobj["pxlm"] = param.data.sortName;
        nowreqobj["pxfs"] = param.data.sortOrder;


        if (reqobj != null) {
          const keys = Object.keys(reqobj);
          keys.forEach((key) => {
            nowreqobj[key] = reqobj[key];
          });
        }
        that.commservice.info("表格的请求数据", url, nowreqobj);
        that.itservice.kwPtPost(url, nowreqobj).subscribe(resp => {
          that.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
            // 去掉获取数据效果
            that.commservice.unblockUI(".loadData");
            if (flag) {
              if (flag2) {
                const addxh_obj = {};
                addxh_obj["total"] = resp["totalRows"];
                const sbsyllList = resp["sbsyllList"];
                addxh_obj["rows"] = sbsyllList.map((item, index) => {
                  const new_obj = {
                    xh: (param.data.pageNumber - 1) * param.data.pageSize + index + 1,
                    sbid: item.sbid,
                    zyl: item.zyl,
                  };
                  const llsyfzList = item.llsyfzList;
                  llsyfzList.forEach((dateobj) => {
                    const fzsj = dateobj.fzsj;
                    const syl = dateobj.syl;
                    new_obj[fzsj] = syl;
                  });
                  return new_obj
                });
                param.success(addxh_obj);
              } else {
                that.commservice.myswal("warning", resp, "", "ts", null);
                const ywerrobj = {};
                ywerrobj["total"] = 0;
                ywerrobj["rows"] = [];
                param.success(ywerrobj);
              }
            }
          })
        });
      },
    });
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .linechart": function (e, value, row, index) {
      this.caozuo_bqid = row.sbid;
      const xAxis_items: any[] = [];
      const items_datas: any[] = [];
      for (let key in row) {
        if (key != "sbid" && key != "xh" && key != "zyl") {
          xAxis_items.push(key);
          items_datas.push(row[key]);
        }
      }
      console.log("xAxis_items", xAxis_items);
      console.log("items_datas", items_datas);
      const zyl = this.commservice.sum(items_datas);  //kb
      this.initchart("onechart", xAxis_items, items_datas, zyl);
      $("#lineChartModal").modal({
        keyboard: true,
        backdrop: "static"
      });
    }.bind(this),
  }

  /**
   * 所有终端加起来的总流量统计
   */
  showallLinechart(): void {
    const url = "sjgz/sbwb/sbsylltj";
    this.itservice.kwPtPost(url, this.s_obj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const sbsylltjList = resp.sbsylltjList;
            const zyl = resp.zyl ? resp.zyl : 0;
            if (sbsylltjList && sbsylltjList.length) {
              const xAxis_items: any[] = [];
              const itemsdata: any[] = [];
              sbsylltjList.forEach((item) => {
                xAxis_items.push(item.fzsj);
                itemsdata.push(item.syl);
              });
              this.initchart("allchart", xAxis_items, itemsdata, zyl);
              $("#lineChartModal").modal({
                keyboard: true,
                backdrop: "static"
              });
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.showallLinechart();
        }
      });
    });
  }

  /**
   *
   * @param {string} type
   * @param xAxis_items
   * @param items_datas
   * @param {number} zyl  ---kb
   */
  initchart(type: string, xAxis_items: any, items_datas: any, zyl: number): void {
    if (this.chart) {
      this.chart.clear();
    } else {
      this.chart = e.init(document.getElementById('lineChart') as HTMLDivElement);
    }
    const option = {
      title: {
        text: "",
        subtext: "",
        subtextStyle: {
          color: "#1477F3",
          fontSize: 15
        },
        left: "center",
        top: "top"
      },
      tooltip: {
        trigger: 'axis',
        //formatter: "{b} <br/>{c}KB"
      },
      toolbox: {
        show: true,
        feature: {
          dataView: { readOnly: false },
          magicType: { type: ['line', 'bar'] },
          restore: {},
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: "16%",
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxis_items,
        axisLine: {
          lineStyle: {
            color: '#000'
          }
        },
        axisLabel: {
          fontSize: 15,
          color: "#000"
        },
        axisTick: {
          show: false,
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        splitNumber: 3,
        minInterval: 1,
        name: "流量(KB)",
        axisLine: {
          lineStyle: {
            color: '#000'
          }
        },
        axisLabel: {
          fontSize: 15,
          color: "#000",
          // formatter: function (v) {
          //   let retstr = "0";
          //   if (v) {
          //     retstr = (v / 1024).toFixed(3);
          //   }
          //   return retstr;
          // }
        },
        splitLine: {
          lineStyle: {
            color: '#ccc'
          }
        },
        axisTick: {
          show: false,
        }
      },
      series: [{
        type: 'line',
        name: '标签流量(KB)',
        data: items_datas,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 10,
        itemStyle: {
          color: "#0ECEFF",
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    };

    //const itcount_mb = zyl ? (zyl / 1024).toFixed(3) : 0;
    if (type == "onechart") {
      option["title"]["text"] = `标签流量统计折线图(${this.caozuo_bqid})`;
      option["title"]["subtext"] = `总流量：${zyl}KB`;
    } else {
      option["title"]["text"] = `标签流量统计折线图(所有终端的流量和)`;
      option["title"]["subtext"] = `总流量：${zyl}KB`;
    }

    this.chart.setOption(option);
  }


  createsearchForm(): void {
    const that = this;
    $("#fzlx").selectpicker();
    this.init_month('init');
    this.init_day("init");
  }


  /**
   * 重置搜索时间
   */
  resetSearchForm(): void {
    const nowfzlx = this.s_obj.fzlx;
    if (nowfzlx == "month") {
      this.init_month("refresh");
    } else if (nowfzlx == "day") {
      this.init_day("refresh");
    }
  }

  /**
   *
   * @param {string} flag
   * init--初始化month
   * refresh---重置month
   */
  init_month(flag: string): void {
    if (flag == "refresh") {
      $("#bDate").selectpicker("destroy");
      $("#eDate").selectpicker("destroy");
    }
    $("#bDate").empty();
    $("#eDate").empty();
    let str: string = "";
    const bdatelist: any[] = []; // 开始时间数据源， 最多12个月
    // 规则，查询时间区间最大为  searchTimeRangeMax_month 个月
    for (let i = 0; i >= -this.searchTimeRangeMax_month; i--) {
      //12 -1
      const addMonth = this.commservice.addMonth(new Date(), i);
      const addMonth_ym = this.commservice.YM_get(addMonth, "separate");
      bdatelist.push(addMonth_ym);
      str += "<option value='" + addMonth_ym + "'>" + addMonth_ym + "</option>";
    }
    $("#bDate").append(str);
    $("#eDate").append(str);
    $("#bDate").selectpicker({
      size: 6
    });
    $("#eDate").selectpicker({
      size: 6
    });
    // 开始时间，赋值为最小
    $("#bDate").selectpicker('val', bdatelist[bdatelist.length - 1]);
  }

  /**
   *
   * @param {string} flag
   * init---初始化day
   * refresh--重置day
   */
  init_day(flag: string): void {
    const that = this;
    const minDate = this.commservice.addDays(new Date(), -this.searchTimeRangeMax_day);
    const maxDate = this.commservice.addDays(new Date(), -1);
    $(".dateB_content").eq(0).val(this.commservice.YMD_get(minDate));
    $(".dateE_content").eq(0).val(this.commservice.YMD_get(new Date()));
    if (flag == "refresh") {
      $(".dateE_content").datepicker("destroy");
      $(".dateB_content").datepicker("destroy");
    }
    $(".dateE_content").datepicker({
      language: "zh-CN",
      todayHighlight: true,
      defaultViewDate: minDate,
      format: "yyyy-mm-dd",
      autoclose: true,
      startDate: minDate,
      endDate: new Date(),
    }).on("changeDate", function (ev) {
      const selectdate = ev.date;  // 当前结束时间
      // 开始时间不能大于 结束时间-1天
      const startMax = that.commservice.addDays(selectdate, -1);
      $(".dateB_content").eq(0).datepicker("setEndDate", startMax);
      // 开始时间不能小于 结束时间 -  searchTimeRangeMax_day 天
      const startMin = that.commservice.addDays(selectdate, -that.searchTimeRangeMax_day);
      $(".dateB_content").eq(0).datepicker("setStartDate", startMin);
    });
    $(".dateB_content").datepicker({
      language: "zh-CN",
      todayHighlight: true,
      defaultViewDate: new Date(),
      format: "yyyy-mm-dd",
      autoclose: true,
      startDate: minDate,
      endDate: maxDate
    }).on("changeDate", function (ev) {
      const selectdate = ev.date;  // 当前开始时间
      // 结束时间不能小于开始时间+ 1天
      const endMin = that.commservice.addDays(selectdate, 1);
      $(".dateE_content").eq(0).datepicker("setStartDate", endMin);
      // 结束时间最大选择不能超过，开始时间 +searchTimeRangeMax_day天
      const endMax = that.commservice.addDays(selectdate, that.searchTimeRangeMax_day);
      if (endMax.getTime() > Date.now()) {
        $(".dateE_content").eq(0).datepicker("setEndDate", new Date());
      } else {
        $(".dateE_content").eq(0).datepicker("setEndDate", endMax);
      }
    });
  }

  /**
   *
   * @param {string} type
   * b--- 开始时间框更改
   * e----结束时间框更改
   */
  dateChange(type: string): void {
    let itv: any; // yyyy-mm 字符串
    if (type == "b") {
      itv = $("#bDate").selectpicker("val");
      // 结束时间的数据源，最小从  itv 开始， 最大不能超过当前月
      const itvarr = itv.split("-");
      const itvDate = new Date(itvarr[0], Number(itvarr[1]) - 1, 1);
      let maxDate: any;
      const addmonthDate = this.commservice.addMonth(itvDate, this.searchTimeRangeMax_month);
      if (addmonthDate.getTime() > Date.now()) {
        // 结束时间数据源，应该从 itv ----当前月
        maxDate = new Date();
      } else {
        // 结束时间数据源，应该从itv ---addmonthDate
        maxDate = addmonthDate;
      }
      // 处理结束时间
      const rangeDatelist = this.commservice.rangeDays_moth(itvDate, maxDate);
      const rangeDatelist_reverse = rangeDatelist.reverse();
      $("#eDate").selectpicker("destroy");
      $("#eDate").empty();
      let str: string = "";
      rangeDatelist_reverse.forEach((datev) => {
        str += "<option value='" + datev + "'>" + datev + "</option>"
      });
      $("#eDate").append(str);
      $("#eDate").selectpicker({
        size: 6
      });
    } else if (type == "e") {
      const bdatestr = $("#bDate").selectpicker("val");
      itv = $("#eDate").selectpicker("val");
      const itvarr = itv.split("-");
      const itvDate = new Date(itvarr[0], Number(itvarr[1]) - 1, 1);
      // 开始时间的数据源， 最大从itv 开始， 最小不能小于 当前 -searchTimeRangeMax_month 个月
      const minDate = this.commservice.addMonth(itvDate, -this.searchTimeRangeMax_month);
      // 处理开始时间
      const rangeDatelist = this.commservice.rangeDays_moth(minDate, itvDate);
      const rangeDatelist_reverse = rangeDatelist.reverse();
      $("#bDate").selectpicker("destroy");
      $("#bDate").empty();
      let str: string = "";
      rangeDatelist_reverse.forEach((datev) => {
        str += "<option value='" + datev + "'>" + datev + "</option>"
      });
      $("#bDate").append(str);
      $("#bDate").selectpicker({
        size: 6
      });
      // 给开始时间赋值为，最初的开始时间（如果最初的开始时间在 此时开始时间数据源中的话）
      if (rangeDatelist_reverse.indexOf(bdatestr) != -1) {
        $("#bDate").selectpicker("val", bdatestr);
      }
    }
  }

  /**
   * 查询方式变更
   * @constructor
   */
  FzlxChange(): void {
    const fzlxv = $("#fzlx").selectpicker("val");
    this.s_obj.fzlx = fzlxv;
    if (fzlxv == "month") {
      $("#MonthRoom").show();
      $("#DayRoom").hide();
    } else if (fzlxv == "day") {
      $("#MonthRoom").hide();
      $("#DayRoom").show();
    }
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      this.initactions(); //用户按钮权限
    });
  }

  constructor(private commservice: CommService,
    private itservice: MyhttpService) {

  }

  ngOnInit() {
    this.getuserinfo();
    this.createsearchForm();
    this.inittable_dzbq();
  }

  ngOnDestroy() {

  }

}
